package com.milo.algorithm.sort;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;

/**
 * @author: Milogenius
 * @create: 2019-07-03 08:53
 * @description: 冒泡排序
 **/
public class BubbleSort {
    public int[] sort(int[] sourceArray){
        //对array进行拷贝,不改变参数内容
        int[] array = Arrays.copyOf(sourceArray, sourceArray.length);
        for (int i = 1; i < array.length; i++) {
            //设计一个标识,若为true,则表示本次循环没有交换数据,也就是待排序列已经有序,排序已经完成
            boolean flag = true;
            for (int j = 0; j < array.length - i; j++) {
                if (array[j]>array[j + 1]) {
                    int tmp = array[j];
                    array[j] = array[j + 1];
                    array[j+1] = tmp;
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
        return array;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
        BubbleSort bubbleSort = new BubbleSort();
        int[] sort = bubbleSort.sort(arr);
        System.out.println("排序后的数组顺序:"+ JSON.toJSONString(sort));
    }
}
